var _origServerURL='';
var _origFolder='';
var _origUid='';
var _origPwd='';
var _origbbcompat='';
var _origoutlookcompat='';
var _origuseheader='';
var _origesc='';

function  _toJavaUrlArray(a) 
{  
  var urlArray = java.lang.reflect.Array.newInstance(java.net.URL, a.length);  
  for (var i = 0; i < a.length; i++) {  
   var url = a[i];  
   java.lang.reflect.Array.set(  
    urlArray,  
    i,  
    (typeof url == "string") ? new java.net.URL(url) : url  
   );  
  }  
  return urlArray;  
} 

function applyConfig()
{
  var cfg=readConfig();
  var children=cfg.documentElement.childNodes;
  
  for(var x=0;x<children.length;x++)
  {
    if(children[x].nodeName=='Sync')
      applySyncConfig(children[x]);
  }
}

function applySyncConfig(node)
{
  var children=node.childNodes;
  var uid='';
  var pwd='';
  var bbcompat='true';
  var outlookcompat='false';
  var useheader='true';
  var esc='false';

  var statusLine=document.getElementById('statuslabel');
  var uidLine=document.getElementById('uid');
  var pwdLine=document.getElementById('pwd');
  var bbcompatcb=document.getElementById('bbcompat');
  var outlookcompatcb=document.getElementById('outlookcompat');
  var useheadercb=document.getElementById('useheader');
  var esccb=document.getElementById('esc');
  
  statusLine.value="Reading config...";
  
  for(var x=0;x<children.length;x++)
  {
    if(children[x].nodeName=='UserID')
      uid=getXMLNodeValue(children[x]);
    if(children[x].nodeName=='Password')
      pwd=getXMLNodeValue(children[x]);
    if(children[x].nodeName=='EscapeCSV')
      esc=getXMLNodeValue(children[x]);
    if(children[x].nodeName=='UseHeader')
      useheader=getXMLNodeValue(children[x]);
    if(children[x].nodeName=='BBCompat')
      bbcompat=getXMLNodeValue(children[x]);
    if(children[x].nodeName=='OutlookCompat')
      outlookcompat=getXMLNodeValue(children[x]);
  }

  if(uid==null) uid='';
  if(pwd==null) pwd='';

  uidLine.value=uid;
  _origUid=uid;
  pwdLine.value=pwd;
  _origPwd=pwd;

  if(bbcompat=='true')
    bbcompatcb.checked=true;
  else
    bbcompatcb.checked=false;
  _origbbcompat=bbcompat;

  if(outlookcompat=='true')
    outlookcompatcb.checked=true;
  else
    outlookcompatcb.checked=false;
  _origoutlookcompat=outlookcompat;

  if(useheader=='true')
    useheadercb.checked=true;
  else
    useheadercb.checked=false;
  _origuseheader=useheader;
  
  if(esc=='true')
    esccb.checked=true;
  else
    esccb.checked=false;
  _origesc=esc;

  statusLine.value="N/A";
}

function resaveConfig()
{
  var uid='';
  var pwd='';
  var bbcompat='true';
  var outlookcompat='false';
  var useheader='true';
  var esc='false';
  var statusLine=document.getElementById('statuslabel');
  var uidLine=document.getElementById('uid');
  var pwdLine=document.getElementById('pwd');
  var bbcompatcb=document.getElementById('bbcompat');
  var outlookcompatcb=document.getElementById('outlookcompat');
  var useheadercb=document.getElementById('useheader');
  var esccb=document.getElementById('esc');
  var changed=false;

  statusLine.value="Checking for changes...";

  uid=uidLine.value;
  pwd=pwdLine.value;
  
  if(bbcompatcb.checked)
    bbcompat='true';
  else
    bbcompat='false';
    
  if(outlookcompatcb.checked)
    outlookcompat='true';
  else
    outlookcompat='false';

  if(useheadercb.checked)
    useheader='true';
  else
    useheader='false';
  
  if(esccb.checked)
    esc='true';
  else
    esc='false';

  if(uid==null) uid='';
  if(pwd==null) pwd='';
  
  uid=uid.trim();
  pwd=pwd.trim();
  _origUid=_origUid.trim();
  _origPwd=_origPwd.trim();

  if(uid!=_origUid)
    changed=true;
  if(pwd!=_origPwd)
    changed=true;

  if(bbcompat!=_origbbcompat)
    changed=true;
  if(outlookcompat!=_origoutlookcompat)
    changed=true;
  if(useheader!=_origuseheader)
    changed=true;
  if(esc!=_origesc)
    changed=true;

  if(changed)
  {
    statusLine.value="Saving configuration...";

    var dom = readConfig();
    var escTextNode=dom.createTextNode(esc);
    var useheaderTextNode=dom.createTextNode(useheader);
    var bbcompatTextNode=dom.createTextNode(bbcompat);
    var outlookcompatTextNode=dom.createTextNode(outlookcompat);
    var uidTextNode=dom.createTextNode(uid);
    var pwdTextNode=dom.createTextNode(pwd);
    var e1=dom.createElement("Sync");
    
    var c1=dom.createElement("EscapeCSV");
    c1.appendChild(escTextNode);
    
    var c2=dom.createElement("UseHeader");
    c2.appendChild(useheaderTextNode);

    var c3=dom.createElement("BBCompat");
    c3.appendChild(bbcompatTextNode);

    var c4=dom.createElement("OutlookCompat");
    c4.appendChild(outlookcompatTextNode);

    var c9=dom.createElement("UserID");
    c9.appendChild(uidTextNode);

    var c10=dom.createElement("Password");
    c10.appendChild(pwdTextNode);

    e1.appendChild(c1);
    e1.appendChild(c2);
    e1.appendChild(c3);
    e1.appendChild(c4);
    e1.appendChild(c9);
    e1.appendChild(c10);

    var children=dom.documentElement.childNodes;
    for(var x=0;x<children.length;x++)
    {
      if(children[x].nodeName=='Sync')
        dom.documentElement.replaceChild(e1,children[x]);
    }
    
    writeConfig(dom);
  }

  statusLine.value="N/A";
}

function importNotes()
{
  var statusLine=document.getElementById('statuslabel');
  var nsIFilePicker = Components.interfaces.nsIFilePicker;
  var fileBox;
  var fileObj;
  var fileChooser;
  var fileName;
  var xmlFile=false;
  var csvFile=false;
  var fileContents='';
  var bbcompatcb=document.getElementById('bbcompat');
  var outlookcompatcb=document.getElementById('outlookcompat');
  var useheadercb=document.getElementById('useheader');
  var esccb=document.getElementById('esc');
  var bbcompat;
  var outlookcompat;
  var useheader;
  var esc;

  bbcompat=bbcompatcb.checked;
  outlookcompat=outlookcompatcb.checked;
  useheader=useheadercb.checked;
  esc=esccb.checked;

  fileChooser = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
  fileChooser.init(window, "Select a file to import notes from",nsIFilePicker.modeOpen);
  if(bbcompat || outlookcompat)
  {
    fileChooser.appendFilter("CSV Files","*.csv");
    fileChooser.appendFilter("XML Files","*.xml");
  }
  else
  {
    fileChooser.appendFilter("XML Files","*.xml");
    fileChooser.appendFilter("CSV Files","*.csv");
  }
  fileBox = fileChooser.show();

  if(fileBox==nsIFilePicker.returnOK || fileBox==nsIFilePicker.returnReplace)
  {
    fileObj=fileChooser.file;
    fileName=fileObj.path;
    if(fileName.length-fileName.toLowerCase().lastIndexOf(".xml")==4)
      xmlFile=true;
    if(fileName.length-fileName.toLowerCase().lastIndexOf(".csv")==4)
      csvFile=true;

    if(csvFile || xmlFile)
    {
      statusLine.value="Importing Notes...";
      fileContents=FileIO.read(fileObj);
      if(xmlFile)
        importXMLFile(fileContents);
      else
      {
        if(bbcompat)
          importBBFile(fileContents);
        else
        {
          if(outlookcompat)
            importOutlookFile(fileContents);
          else
            importCsvFile(fileContents,useheader,esc);
        }
      }
      statusLine.value="N/A";
    }
    else
      alert('Currently, only XML and CSV files are supported');
  }
}

function importXMLFile(fileContents)
{
  var parser = new DOMParser();
  var dom = parser.parseFromString(fileContents, "text/xml");
  var notecount=0;
  var children;  
  var d=new Date();
  var idx=d.getTime();
  
  children=dom.documentElement.childNodes;
  for(var x=0;x<children.length;x++)
  {
    if(children[x].nodeName=='ThunderNote')
    {
      importThunderNoteNode(children[x],idx+notecount);
      notecount++;
    }
  }
  
  alert(notecount+' Notes imported');
}

function importThunderNoteNode(xmlNode,idx)
{
  var children=xmlNode.childNodes;
  var title='',note='',createdtg='',moddtg='',pvt='true';
  var d=new Date();
  var pvt2=true;
  var idx2=d.getTime();
  
  for(var x=0;x<children.length;x++)
  {
    if(children[x].nodeName=='Title')
      title=getXMLNodeValue(children[x]);
    if(children[x].nodeName=='Body')
      note=getXMLNodeValue(children[x]);
    if(children[x].nodeName=='CreationDTG')
      createdtg=getXMLNodeValue(children[x]);
    if(children[x].nodeName=='UpdateDTG')
      moddtg=getXMLNodeValue(children[x]);
    if(children[x].nodeName=='Private')
      pvt=getXMLNodeValue(children[x]);
  }

  if(pvt=='false')
    pvt2=false;
  title=unescape(title);
  note=unescape(note);
  opener.createNewNote(title,note,idx,-1,'',idx2,idx2,pvt2);
}

function importOutlookFile(fileContents)
{
  var stringarray=CSVToArray(fileContents),note;
  var counter=0; 
  var notecount=0;
  var d=new Date();
  var idx=d.getTime();
  var note,note2,title,crat;
    
  for(counter=0;counter<stringarray.length;counter++)
  {
    // skip the header
    if(counter>0)
    {
      // if there are 5 fields, its valid. if not, it is not a full note
      if(stringarray[counter].length==5)
      {
        // the note body is the first array element
        note=stringarray[counter][0];
        note=note.trim();
        if(note!='')
        {
          crat=note.indexOf('\n');
          if(crat!=-1)
          {
            title=note.substring(0,crat);
            title=title.trim();
            note2=note.substring(crat);
            note2=note2.trim();
            note2='\n'+note2;
          }
          else
          {
            title=note.trim();
            note2='';
          }
  
          opener.createNewNote(title,note2,idx+notecount,-1,'',idx,idx,false);
          notecount++;
        }
      }
    }
  }

  alert(notecount+' Notes imported');
}

function importBBFile(fileContents)
{
  var stringarray=CSVToArray(fileContents),note;
  var counter=0; 
  var notecount=0;
  var d=new Date();
  var idx=d.getTime();
  var note,title;
    
  for(counter=0;counter<stringarray.length;counter++)
  {
    // skip the header
    if(counter>0)
    {
      // if there are 3 fields, its valid. if not, it is not a full note
      if(stringarray[counter].length==3)
      {
        // the note title is the first array element, the body is the second
        note=stringarray[counter][0];
        title=stringarray[counter][1];
        note=note.trim();
        title=title.trim();
        if(note!='' && title!='')
        {
          opener.createNewNote(title,note,idx+notecount,-1,'',idx,idx,false);
          notecount++;
        }
      }
    }
  }

  alert(notecount+' Notes imported');
}

function importCsvFile(fileContents,useheader,esc)
{
  var stringarray=fileContents.split('\"\r\n');
  var note;
  var stringarray2;
  var note2,title;
  var notecount=0;
  var d=new Date();
  var idx=d.getTime();
  
  for(var x=0;x<stringarray.length;x++)
  {
    note=stringarray[x];
    note=note.trim();
    if(note!='')
    {
      if((useheader && notecount>0) || !useheader)
      {
        if(esc)
        {
          stringarray2=note.split(',');
          if(stringarray2.length==4)
          {
            title=stringarray2[0];
            title=title.substring(0,title.length-1);
            title=title.substring(1);
            title=title.trim();
            note2=stringarray2[1];
            note2=note2.substring(0,note2.length-1);
            note2=note2.substring(1);
            note2=note2.trim();
            title=unescape(title);
            note2=unescape(note2);
            title=title.trim();
            note2=note2.trim();
            note2='\n'+note2;
    
            opener.createNewNote(title,note2,idx+notecount,-1,'',idx,idx,false);
            notecount++;
          }
        }
        else
        {
          stringarray2=note.split('\",\"');
          if(stringarray2.length==4)
          {
            title=stringarray2[0];
            title=title.substring(1);
            title=title.trim();
            note2=stringarray2[1];
            note2=note2.substring(1);
            note2=note2.trim();
            title=title.trim();
            note2=note2.trim();
            note2='\n'+note2;
    
            opener.createNewNote(title,note2,idx+notecount,-1,'',idx,idx,false);
            notecount++;
          }
        }
      }
      else
        notecount++;
    }
  }
  
  if(useheader && notecount>0)
    notecount--;
  alert(notecount+' Notes imported');
}

function exportNotes()
{
  var statusLine=document.getElementById('statuslabel');
  var bbcompatcb=document.getElementById('bbcompat');
  var outlookcompatcb=document.getElementById('outlookcompat');
  var useheadercb=document.getElementById('useheader');
  var esccb=document.getElementById('esc');
  var bbcompat;
  var outlookcompat;
  var useheader;
  var esc;

  var nsIFilePicker = Components.interfaces.nsIFilePicker;
  var fileBox;
  var fileObj;
  var fileChooser;
  var fileName;
  var xmlFile=false;
  var csvFile=false;
  var dom,children;
  var notecount=0;
  
  bbcompat=bbcompatcb.checked;
  outlookcompat=outlookcompatcb.checked;
  useheader=useheadercb.checked;
  esc=esccb.checked;

  fileChooser = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
  fileChooser.init(window, "Select a file to export your notes to",nsIFilePicker.modeSave);
  if(bbcompat || outlookcompat)
  {
    fileChooser.appendFilter("CSV Files","*.csv");
    fileChooser.appendFilter("XML Files","*.xml");
  }
  else
  {
    fileChooser.appendFilter("XML Files","*.xml");
    fileChooser.appendFilter("CSV Files","*.csv");
  }
  fileBox = fileChooser.show();
  
  if(fileBox==nsIFilePicker.returnOK || fileBox==nsIFilePicker.returnReplace)
  {
    fileObj=fileChooser.file;
    fileName=fileObj.path;
    if(fileName.length-fileName.toLowerCase().lastIndexOf(".xml")==4)
      xmlFile=true;
    if(fileName.length-fileName.toLowerCase().lastIndexOf(".csv")==4)
      csvFile=true;

    if(csvFile || xmlFile)
    {
      statusLine.value="Exporting Notes...";

      if(xmlFile)
        FileIO.write(fileObj,"<ThunderNotes>\n");
      else
      {
        if(bbcompat)
          FileIO.write(fileObj,"\"Note Title\",\"Note Body\",\"Categories\"\r\n");
        else
        {
          if(outlookcompat)
            FileIO.write(fileObj,"\"Note Body\",\"Categories\",\"Note Color\",\"Priority\",\"Sensitivity\"\r\n");
          else
          {
            if(useheader)
              FileIO.write(fileObj,"\"Title\",\"Body\",\"CreationDTG\",\"UpdateDTG\"\r\n");
            else
              FileIO.write(fileObj,"");
          }
        }
      }
      
      // cycle through all notes
      dom = readThunderNotes();
      children=dom.documentElement.childNodes;
      for(var x=0;x<children.length;x++)
      {
        if(children[x].nodeName=='ThunderNote')
        {
          exportThunderNoteNode(children[x],csvFile,xmlFile,bbcompat,outlookcompat,esc,fileObj);
          notecount++;
        }
      }
      if(xmlFile)
        FileIO.write(fileObj,"</ThunderNotes>",'a');
        
      alert(notecount+' Notes exported');
      statusLine.value="N/A";
    }
    else
      alert('Currently, only XML and CSV files are supported');
  }
}

function exportThunderNoteNode(xmlNode,isCsv,isXml,bbcompat,outlookcompat,esc,theFile)
{
  var children=xmlNode.childNodes;
  var title='',note='',createdtg='',moddtg='';
  
  for(var x=0;x<children.length;x++)
  {
    if(children[x].nodeName=='Title')
      title=getXMLNodeValue(children[x]);
    if(children[x].nodeName=='Body')
      note=getXMLNodeValue(children[x]);
    if(children[x].nodeName=='CreationDTG')
      createdtg=getXMLNodeValue(children[x]);
    if(children[x].nodeName=='UpdateDTG')
      moddtg=getXMLNodeValue(children[x]);
  }

  if(title.indexOf(' ')!=-1)
    title=escape(title);
  if(note.indexOf(' ')!=-1)
    note=escape(note);

  if(isXml)
  {
    FileIO.write(theFile,'  <ThunderNote>\n','a');

    FileIO.write(theFile,'    <Title>','a');
    FileIO.write(theFile,title,'a');
    FileIO.write(theFile,'</Title>\n','a');

    FileIO.write(theFile,'    <Body>','a');
    FileIO.write(theFile,note,'a');
    FileIO.write(theFile,'</Body>\n','a');

    FileIO.write(theFile,'    <CreationDTG>','a');
    FileIO.write(theFile,createdtg,'a');
    FileIO.write(theFile,'</CreationDTG>\n','a');

    FileIO.write(theFile,'    <UpdateDTG>','a');
    FileIO.write(theFile,moddtg,'a');
    FileIO.write(theFile,'</UpdateDTG>\n','a');

    FileIO.write(theFile,'  </ThunderNote>\n','a');
  }
  else
  {
    if(bbcompat)
    {
      title=unescape(title);
      note=unescape(note);
      note=note.replace(/\"/g,'\"\"');
      FileIO.write(theFile,'\"','a');
      FileIO.write(theFile,title,'a');
      FileIO.write(theFile,'\",\"','a');
      FileIO.write(theFile,note,'a');
      FileIO.write(theFile,'\",\r\n','a');
    }
    else
    {
      if(outlookcompat)
      {
        title=unescape(title);
        note=unescape(note);
        note=note.replace(/\"/g,'\"\"');
        FileIO.write(theFile,'\"','a');
        FileIO.write(theFile,title,'a');
        //FileIO.write(theFile,'\n','a');
        FileIO.write(theFile,note,'a');
        FileIO.write(theFile,'\",,\"3\",\"Normal\",\"Normal\"\r\n','a');
      }
      else
      {
        if(!esc)
        {
          title=unescape(title);
          note=unescape(note);
          note=note.replace(/\"/g,'\"\"');
        }
        
        FileIO.write(theFile,'\"','a');
        FileIO.write(theFile,title,'a');
        FileIO.write(theFile,'\",\"','a');
        FileIO.write(theFile,note,'a');
        FileIO.write(theFile,'\",\"','a');
        FileIO.write(theFile,createdtg,'a');
        FileIO.write(theFile,'\",\"','a');
        FileIO.write(theFile,moddtg,'a');
        FileIO.write(theFile,'\"\r\n','a');
      }
    }
  }
}

function clickedBB()
{
  var bbcompatcb=document.getElementById('bbcompat');
  var outlookcompatcb=document.getElementById('outlookcompat');
  var useheadercb=document.getElementById('useheader');
  var esccb=document.getElementById('esc');
  
  if(bbcompatcb.checked)
  {
    // this actually gets called before the change so if we get here, it means we are unchecking the box
  }
  else
  {
    useheadercb.checked=true;
    esccb.checked=false;
    outlookcompatcb.checked=false;
  }
}

function clickedOutlook()
{
  var bbcompatcb=document.getElementById('bbcompat');
  var outlookcompatcb=document.getElementById('outlookcompat');
  var useheadercb=document.getElementById('useheader');
  var esccb=document.getElementById('esc');
  
  if(outlookcompatcb.checked)
  {
    // this actually gets called before the change so if we get here, it means we are unchecking the box
  }
  else
  {
    useheadercb.checked=true;
    esccb.checked=false;
    bbcompatcb.checked=false;
  }
}

function sync()
{
  syncHelipad();
}

function syncHelipad()
{
  var d=new Date();
  var dstring=d.toString();
  var savorstd;
  if(dstring.indexOf('Standard')!=-1)
    savorstd='Standard';
  else
    savorstd='Savings';

  var localUTCOffset = d.getTimezoneOffset() * 60000;
  
  //d.setTime(1258308773033);
  //alert(d);
  //if(savorstd=='Standard')
  //  alert(createHelipadDateFromDateObject(d,0,0));
  //else    
  //  alert(createHelipadDateFromDateObject(d,1,0));

  //d.setTime(1258308773311);
  //alert(d);
  //if(savorstd=='Standard')
  //  alert(createHelipadDateFromDateObject(d,0,0));
  //else    
  //  alert(createHelipadDateFromDateObject(d,1,0));
  
  //d=createDateFromHelipadDateString('2009-11-15T18:12:49+00:00');
  //alert(d);
  
  //return;
  /*
  var d=new Date();
  var localUTCOffset = d.getTimezoneOffset() * 60000;
  var td1=createDateFromHelipadDateString("2009-08-31T01:05:11+01:00"); // get helipad date as local  - UTC is 31 Aug 09 00:05:11
  var td2=createDateFromThunderNoteDateString("8-30-2009 20:05:11");    // get thundernote date as lcoal
  
  
  
  // gotta update createHelipadDateFromDateObject to take local and return UTC
  
  alert(td1.toLocaleString());
  alert(td2.toLocaleString());
  alert(createHelipadDateFromDateObject(td2,1,0));
  return;
  */
  
  //d.setTime(1258308769000);
  //var dstring=d.toString();
  //var savorstd;;
  
  //if(dstring.indexOf('Standard')!=-1)
  //  savorstd='Standard';
  //else
  //  savorstd='Savings';
  //alert(d);
  //alert(dstring);
  //alert(savorstd);
  //alert(d.getTimezoneOffset());
  //alert('2009-11-14T00:53:09+00:00');
  //if(savorstd=='Standard')
  //  alert(createHelipadDateFromDateObject(d,0,0));
  //else    
  //  alert(createHelipadDateFromDateObject(d,1,0));
  //alert(createDateFromHelipadDateString('2009-11-14T00:53:09+00:00'));
  //2009-11-14T00:53:09+00:00
  //return;
  
  // 1258159756174 (13 Nov 2009 1949 should convert to 2009-11-14T00:49:09+00:00)
  
  
  var cfg=readSyncDB();
  var dom,children,children2,children3,children4,children5,children6,children7;
  var providers,helipadprovider,helipadurl,helipadlast,helipadoffsethrssav,helipadoffsetminssav,helipadoffsethrsstd,helipadoffsetminsstd,helppadmaxdiff;
  var txtHelipadUrl,txtHelipadLast;
  var newTime,newTimeUTC;
  var oldTime,oldTimeUTC;
  var objectTime,objectTime2;
  var idx,maxdiff;
  var statusLine=document.getElementById('statuslabel');
  var uidLine=document.getElementById('uid');
  var pwdLine=document.getElementById('pwd');
  var syncTypeLine=document.getElementById('hpSyncOption');
  var usehrsoffset,useminsoffset;
  var tempdate1,tempdate2,tempdatestring1,tempdatestring2;
  
  statusLine.value="Reading Helipad Configuration...";
  providers=cfg.getElementsByTagName('SyncProviders');
  helipadprovider=providers[0].getElementsByTagName('Helipad');
  helipadurl=helipadprovider[0].getElementsByTagName('RootURL');
  helipadoffsethrssav=helipadprovider[0].getElementsByTagName('OffsetHoursSavings');
  helipadoffsetminssav=helipadprovider[0].getElementsByTagName('OffsetMinutesSavings');
  helipadoffsethrsstd=helipadprovider[0].getElementsByTagName('OffsetHoursStandard');
  helipadoffsetminsstd=helipadprovider[0].getElementsByTagName('OffsetMinutesStandard');
  helipadmaxdiff=helipadprovider[0].getElementsByTagName('MaximumDifference');
  helipadlast=helipadprovider[0].getElementsByTagName('LastSync');
  txtHelipadUrl=helipadurl[0].childNodes[0].nodeValue;
  txtHelipadLast=helipadlast[0].childNodes[0].nodeValue;
  oldTime=parseInt(txtHelipadLast,10);
  oldTimeUTC=oldTime+localUTCOffset;
  if(savorstd=='Standard')
  {
    usehrsoffset=helipadoffsethrsstd[0].childNodes[0].nodeValue;
    useminsoffset=helipadoffsetminsstd[0].childNodes[0].nodeValue;
  }
  else
  {
    usehrsoffset=helipadoffsethrssav[0].childNodes[0].nodeValue;
    useminsoffset=helipadoffsetminssav[0].childNodes[0].nodeValue;
  }    

  maxdiff=helipadmaxdiff[0].childNodes[0].nodeValue;
  statusLine.value="Synchronizing changes...";

  var uid=uidLine.value;
  var pwd=pwdLine.value;
  var syncType=syncTypeLine.value;
  
  var docs,counter,counter2;
  var authOk=false;
  var noteFound=false;
  var v1,v2,v3,v4,v5,v6,v7,v8;
  
  __HELIPAD.setRootUrl(txtHelipadUrl);
  
  
  statusLine.value="Checking authentication...";
  authOk=__HELIPAD.checkCredentials(uid,pwd);
  if(authOk)
  {
    if(syncType=='UPLOAD')
    {
      if(confirm('This will remove all current notes from Helipad and upload all current ThunderNotes. Please confirm'))
      {
        statusLine.value="Retrieving Documents...";
        docs=__HELIPAD.getDocs(uid,pwd);

        // remember the time right now so any new updates will get caught on next sync
        newTime=d.getTime();
        newTimeUTC=newTime+localUTCOffset;

        statusLine.value="Purging Helipad notes...";
        // Delete all Helipad notes
        for(counter=0;counter<docs.length;counter++)
        {
          if(!__HELIPAD.deleteDoc(uid,pwd,docs[counter].id))
          {
            alert('An error occurred deleting the Helipad note titled \"'+docs[counter].title+'\"');
          }
        }
        
        statusLine.value="Updating Helipad from ThunderNote...";
        // Add all ThunderNotes to Helipad
        dom = readThunderNotes();
        children=dom.getElementsByTagName('ApplicationNotes');
        children2=dom.getElementsByTagName('Title');
        children3=dom.getElementsByTagName('CreationDTG');
        children4=dom.getElementsByTagName('UpdateDTG');
        children5=dom.getElementsByTagName('Body');
        children6=dom.getElementsByTagName('Category');
        children7=dom.getElementsByTagName('SearchTerms');
        children8=dom.getElementsByTagName('Private');
        for(counter=0;counter<children.length;counter++)
        {
          // skip private notes
          if(children8[counter].childNodes[0]!=null)
          {
            if(children8[counter].childNodes[0].nodeValue=='false')
              v7=false;
            else
              v7=true;
          }
          else
            v7=true;

          if(!v7)
          {
            //tempdate1=new Date();
            tempdate2=new Date();
            
            if(!__HELIPAD.createDoc(uid,pwd,unescape(children2[counter].childNodes[0].nodeValue),unescape(children5[counter].childNodes[0].nodeValue),children[counter].childNodes[0].nodeValue))
            {
              alert('An error occurred creating the Helipad note titled \"'+children2[counter].childNodes[0].nodeValue+'\"');
            }
            else
            {
              // update the thundernote that we just sent so that the UpdatedDTG is right now and matches the
              // change date on the Helipad note. The HP note will have a create and update date of now.
              
              if(children2[counter].childNodes[0]!=null)
                v1=unescape(children2[counter].childNodes[0].nodeValue);
              else
                v1='';
                
              if(children5[counter].childNodes[0]!=null)
                v2=unescape(children5[counter].childNodes[0].nodeValue);
              else
                v2='';
              
              if(children[counter].childNodes[0]!=null)
                v3=children[counter].childNodes[0].nodeValue;
              else
                v3='';
  
              if(children6[counter].childNodes[0]!=null)
                v4=children6[counter].childNodes[0].nodeValue;
              else
                v4='';
  
              if(children7[counter].childNodes[0]!=null)
                v5=children7[counter].childNodes[0].nodeValue;
              else
                v5='';
                
              if(children3[counter].childNodes[0]!=null)
                v6=children3[counter].childNodes[0].nodeValue;
              else
                v6='';
              
              opener.modifyExistingNote(  v1,
                                          v2,
                                          v3,
                                          v4,
                                          v5,
                                          false,
                                          v6,
                                          tempdate2.getTime(),
                                          v7);
            }
          }
        }

        // Get a new time so that it is AFTER all the adds we just did
        d=new Date();
        newTime=d.getTime();

        statusLine.value="Writing Helipad Configuration...";
        // Update sync time and write config
        helipadlast[0].childNodes[0].nodeValue=newTime;
        writeSyncDB(cfg);
        
        alert('Helipad has been initialized with all ThunderNotes.');
      }
    }

    if(syncType=='DOWNLOAD')
    {
      if(confirm('This will remove all current ThunderNotes and download all current Helipad notes. Please confirm'))
      {
        statusLine.value="Retrieving Documents...";
        docs=__HELIPAD.getDocs(uid,pwd);
                
        statusLine.value="Purging ThunderNotes...";
        // Remove all ThunderNotes
        dom = readThunderNotes();
        children=dom.getElementsByTagName('ApplicationNotes');
        children2=dom.getElementsByTagName('Title');
        children3=dom.getElementsByTagName('CreationDTG');
        children4=dom.getElementsByTagName('UpdateDTG');
        children5=dom.getElementsByTagName('Body');
        for(counter=0;counter<children.length;counter++)
        {
          opener.removeNote(children[counter].childNodes[0].nodeValue);
          // see about updating the list
        }

        statusLine.value="Updating ThunderNote from Helipad...";
        // Add notes from Helipad
        for(counter=0;counter<docs.length;counter++)
        {
          d=new Date();
          idx=d.getTime();
          
          
          // gotta turn the Helipad date into a TNote date and pass it into createNewNote
          
          tempdate1=createDateFromHelipadDateString(docs[counter].updatedOn);
          opener.createNewNote(docs[counter].title,docs[counter].source,idx,'-1','',tempdate1.getTime(),tempdate1.getTime(),false);
  
          // see about updating the list
          
          if(!__HELIPAD.updateTag(uid,pwd,idx,docs[counter].id))
          {
            alert('An error occurred updating the Helipad note titled \"'+docs[counter].title+'\" with a new ThunderNote ID');
          }
        }

        // Get a new time so that it is AFTER all the adds we just did
        d=new Date();
        newTime=d.getTime();
        
        statusLine.value="Writing Helipad Configuration...";
        // Update sync time and write config
        helipadlast[0].childNodes[0].nodeValue=newTime;
        writeSyncDB(cfg);

        alert('ThunderNotes has been initialized with all Helipad notes. For the notes to appear properly in the GUI, you must close and re-open the ThunderNotes screen.');
      }
    }

    if(syncType=='NORMAL')
    {
      statusLine.value="Retrieving Documents...";
      docs=__HELIPAD.getDocs(uid,pwd);
      
      // remember the time right now so any new updates will get caught on next sync
      newTime=d.getTime();
  
      statusLine.value="Checking for new notes in Helipad...";
      // Check for new notes in Helipad. If a note exists in Helipad with a thunderNoteID of -1, that means it was
      // added new to Helipad but not ThunderNote
      for(counter=0;counter<docs.length;counter++)
      {
        if(docs[counter].thunderNoteID==-1)
        {
          if(confirm('A new note titled : \"'+docs[counter].title+'\" has been added to Helipad. Add it to ThunderNote too?'))
          {
            // add the note to ThunderNote (and update the HeliPad note with the new ThunderNote ID)
            tempdate2=new Date();

            if(__HELIPAD.updateTag(uid,pwd,tempdate2.getTime(),docs[counter].id))
            {
              opener.createNewNote(docs[counter].title,docs[counter].source,tempdate2.getTime(),'-1','',tempdate2.getTime(),tempdate2.getTime(),false);
            }            
          }
        }
      }
      
      statusLine.value="Checking for new notes in ThunderNote and deleted notes from Helipad...";
      // Check for new notes in ThunderNote. If a note exists in ThunderNote and a corresponding note cannot be found in
      // Helipad with the same thunderNoteID, that means:
      //  1. The note was added to ThunderNote but not Helipad; or
      //  2. The note was deleted from Helipad but not ThunderNote.
      dom = readThunderNotes();
      children=dom.getElementsByTagName('ApplicationNotes');
      children2=dom.getElementsByTagName('Title');
      children3=dom.getElementsByTagName('CreationDTG');
      children4=dom.getElementsByTagName('UpdateDTG');
      children5=dom.getElementsByTagName('Body');
      children6=dom.getElementsByTagName('Category');
      children7=dom.getElementsByTagName('SearchTerms');
      children8=dom.getElementsByTagName('Private');
      for(counter=0;counter<children.length;counter++)
      {
        if(children8[counter].childNodes[0]!=null)
        {
          if(children8[counter].childNodes[0].nodeValue=='false')
            v7=false;
          else
            v7=true;
        }
        else
          v7=true;

        //.childNodes[0].nodeValue
        noteFound=false;
        for(counter2=0;counter2<docs.length;counter2++)
        {
          if(children[counter].childNodes[0].nodeValue==docs[counter2].thunderNoteID)
          {
            noteFound=true;
            break;
          }
        }
        
        // only add then new note to HeliPad if the "Private" flag was not checked
        if(!noteFound && !v7)
        {
          // If the ThunderNote createDTG is greater than the last sync DTG, its new, otherwise it was deleted from Helipad
          //objectTime=createDateFromThunderNoteDateString(children3[counter].childNodes[0].nodeValue);
          objectTime=new Date();
          objectTime.setTime(children3[counter].childNodes[0].nodeValue);
          if(objectTime.getTime()>oldTime)
          {
            if(confirm('A new note titled : \"'+unescape(children2[counter].childNodes[0].nodeValue)+'\" has been added to ThunderNote. Add it to Helipad too?'))
            {
              // add the note to Helipad (and update the ThunderNote update DTG to reflect now)
              tempdate2=new Date();
  
              if(__HELIPAD.createDoc(uid,pwd,unescape(children2[counter].childNodes[0].nodeValue),unescape(children5[counter].childNodes[0].nodeValue),children[counter].childNodes[0].nodeValue))
              {
                if(children2[counter].childNodes[0]!=null)
                  v1=unescape(children2[counter].childNodes[0].nodeValue);
                else
                  v1='';
                  
                if(children5[counter].childNodes[0]!=null)
                  v2=unescape(children5[counter].childNodes[0].nodeValue);
                else
                  v2='';
                
                if(children[counter].childNodes[0]!=null)
                  v3=children[counter].childNodes[0].nodeValue;
                else
                  v3='';
    
                if(children6[counter].childNodes[0]!=null)
                  v4=children6[counter].childNodes[0].nodeValue;
                else
                  v4='';
    
                if(children7[counter].childNodes[0]!=null)
                  v5=children7[counter].childNodes[0].nodeValue;
                else
                  v5='';
                  
                if(children3[counter].childNodes[0]!=null)
                  v6=children3[counter].childNodes[0].nodeValue;
                else
                  v6='';

                if(children8[counter].childNodes[0]!=null)
                {
                  if(children8[counter].childNodes[0].nodeValue=='false')
                    v7=false;
                  else
                    v7=true;
                }
                else
                  v7=true;

                opener.modifyExistingNote(  v1,
                                            v2,
                                            v3,
                                            v4,
                                            v5,
                                            false,
                                            v6,
                                            tempdate2.getTime(),
                                            v7);
              }            

            }
          }
          else
          {
            if(confirm('A note titled : \"'+unescape(children2[counter].childNodes[0].nodeValue)+'\" was deleted from Helipad. Delete it from ThunderNote too?'))
            {
              // delete the note from ThunderNote
              opener.removeNote(children[counter].childNodes[0].nodeValue);
            }
          }
        }
      }

      statusLine.value="Checking for deleted notes in ThunderNote...";
      for(counter=0;counter<docs.length;counter++)
      {
        if(docs[counter].thunderNoteID!=-1)
        {
          noteFound=false;
          for(counter2=0;counter2<children.length;counter2++)
          {
            if(children[counter2].childNodes[0].nodeValue==docs[counter].thunderNoteID)
            {
              noteFound=true;
              break;
            }
          }
          
          if(!noteFound)
          {
            if(confirm('A note titled : \"'+docs[counter].title+'\" was deleted from ThunderNote. Delete it from Helipad too?'))
            {
              // delete the note from Helipad
              if(!__HELIPAD.deleteDoc(uid,pwd,docs[counter].id))
              {
                alert('An error occurred updating the Helipad note titled \"'+docs[counter].title+'\" with a new ThunderNote ID');
              }
            }
          }
        }
      }

      statusLine.value="Checking for changed notes in Helipad...";
      for(counter=0;counter<docs.length;counter++)
      {
        if(docs[counter].thunderNoteID!=-1)
        {
          noteFound=false;
          for(counter2=0;counter2<children.length;counter2++)
          {
            if(children[counter2].childNodes[0].nodeValue==docs[counter].thunderNoteID)
            {
              noteFound=true;
              break;
            }
          }
          
          if(noteFound)
          {
            
            // there is something fucked up here. for example, if Helipad is init'd from TN, TN has original dates
            // but Helipad dates will be the date the init was done, which is wrong. we need to manually set
            // dates in TN and HP
            
            objectTime2=new Date();
            // Get the updated Date for each of the ThunderNote and Helipad notes
            objectTime=createDateFromHelipadDateString(docs[counter].updatedOn);                            // HP updated
            objectTime2.setTime(children4[counter2].childNodes[0].nodeValue);   // TN updated
            tempdate1=new Date();
            tempdate1.setTime(txtHelipadLast);
            
            // only do anything at all if the last changed date on the local or remote note is newer than
            // the last sync date
            if(objectTime.getTime()>tempdate1.getTime() || objectTime2.getTime()>tempdate1.getTime())
            {
              if(Math.abs(objectTime.getTime()-objectTime2.getTime())>maxdiff)
              {
                if(objectTime.getTime()>objectTime2.getTime())
                {
                  if(confirm('A new note titled : \"'+docs[counter].title+'\" was changed in Helipad. Download the changes to ThunderNote?'))
                  {
                    // download the changes to TN
                    //-----
                    if(docs[counter].title!=null)
                      v1=docs[counter].title;
                    else
                      v1='';
                      
                    if(docs[counter].source!=null)
                      v2=docs[counter].source;
                    else
                      v2='';
                    
                    if(children[counter2].childNodes[0]!=null)
                      v3=children[counter2].childNodes[0].nodeValue;
                    else
                      v3='';
        
                    if(children6[counter2].childNodes[0]!=null)
                      v4=children6[counter2].childNodes[0].nodeValue;
                    else
                      v4='';
        
                    if(children7[counter2].childNodes[0]!=null)
                      v5=children7[counter2].childNodes[0].nodeValue;
                    else
                      v5='';
                      
                    if(children3[counter2].childNodes[0]!=null)
                      v6=children3[counter2].childNodes[0].nodeValue;
                    else
                      v6='';
                    
                    v7=false;
                    
                    alert(v1);
                    alert(v2);
                    opener.modifyExistingNote(  v1,
                                                v2,
                                                v3,
                                                v4,
                                                v5,
                                                false,
                                                v6,
                                                objectTime.getTime(),
                                                v7);
                    //-----
                  }
                }
                else
                {
                  if(confirm('A note titled : \"'+docs[counter].title+'\" was changed in ThunderNote. Upload the changes to Helipad?'))
                  {
                    // upload changes to HP
                    //-----
                    //tempdate1=new Date();
                    tempdate2=new Date();
                    
                    if(!__HELIPAD.updateDoc(uid,pwd,unescape(children2[counter].childNodes[0].nodeValue),unescape(children5[counter].childNodes[0].nodeValue),children[counter].childNodes[0].nodeValue,docs[counter].id))
                    {
                      alert('An error occurred updating the Helipad note titled \"'+children2[counter].childNodes[0].nodeValue+'\"');
                    }
                    else
                    {
                      // update the thundernote that we just sent so that the UpdatedDTG is right now and matches the
                      // change date on the Helipad note. The HP note will have a create and update date of now.
                      
                      if(children2[counter].childNodes[0]!=null)
                        v1=unescape(children2[counter].childNodes[0].nodeValue);
                      else
                        v1='';
                        
                      if(children5[counter].childNodes[0]!=null)
                        v2=unescape(children5[counter].childNodes[0].nodeValue);
                      else
                        v2='';
                      
                      if(children[counter].childNodes[0]!=null)
                        v3=children[counter].childNodes[0].nodeValue;
                      else
                        v3='';
          
                      if(children6[counter].childNodes[0]!=null)
                        v4=children6[counter].childNodes[0].nodeValue;
                      else
                        v4='';
          
                      if(children7[counter].childNodes[0]!=null)
                        v5=children7[counter].childNodes[0].nodeValue;
                      else
                        v5='';
                        
                      if(children3[counter].childNodes[0]!=null)
                        v6=children3[counter].childNodes[0].nodeValue;
                      else
                        v6='';
                        
                      v7=false;
                      
                      opener.modifyExistingNote(  v1,
                                                  v2,
                                                  v3,
                                                  v4,
                                                  v5,
                                                  false,
                                                  v6,
                                                  tempdate2.getTime(),
                                                  v7);
                    }


                    //-----
                  } // end confirm
                } // end time check
              }
              
              //alert(Math.abs(objectTime.getTime()-objectTime2.getTime()));
              
              //// Confirm that the Helipad note was updated AFTER the last time we Synced
              //if(objectTime.getTime()>oldTime)
              //{
              //  // If the difference between the ThunderNote and Helipad updates is greater than 10 milliseconds, update ThunderNote
              //  if(Math.abs(objectTime.getTime()-objectTime2.getTime())>getMaxDifferenceMillis())
              //  {
              //    if(confirm('A note titled : \"'+docs[counter].title+'\" was changed in Helipad. Update it in ThunderNote too?'))
              //    {
              //      // update ThunderNote
              //    }
              //  }
              //}            
            } 
          }
        }
      }
      
      // new note in HP needs to be added to TN - done
      // new note in TN needs to be added to HP - done
      // note deleted from HP needs to be deleted from TN - done
      // note deleted from TN needs to be deleted from HP - done
      // note changed in HP needs to change in TN
      // note changed in TN needs to change in HP
      
      
      // Get a new time so that it is AFTER all the changes we just did
      d=new Date();
      newTime=d.getTime();
    
      statusLine.value="Writing Helipad Configuration...";
      // Update sync time and write config
      helipadlast[0].childNodes[0].nodeValue=newTime;
      writeSyncDB(cfg);
    
    }
  }
  else
    alert('Authentication to Helipad failed, please double check your User ID, password and network connection.');  //alert(authOk);
  
  statusLine.value="N/A";
}

function oldsync()
{
  // this is just here to get the old code out of the way and try to preserve it in case we need it in the future
  
  
  //var paths=new Array();
  //var tnjarpath;
  //var syncmljar1path;
  //var syncmljar2path;
  //var syncmljar3path;
  //var cl;
  //var loadedClass;
  //var classInst;

  //serverurl=urlLine.value;
  //foldername=folderLine.value;
  
  /*
  tnjarpath=getJarFileLocalPath('thundernote.jar');
  tnjarpath=tnjarpath.replace(/\\/g,'/');
  tnjarpath='file:///'+tnjarpath;

  syncmljar1path=getJarFileLocalPath('funambol-j2me-common.jar');
  syncmljar1path=syncmljar1path.replace(/\\/g,'/');
  syncmljar1path='file:///'+syncmljar1path;

  syncmljar2path=getJarFileLocalPath('funambol-j2me-syncml.jar');
  syncmljar2path=syncmljar2path.replace(/\\/g,'/');
  syncmljar2path='file:///'+syncmljar2path;

  syncmljar3path=getJarFileLocalPath('funambol-j2me-mail.jar');
  syncmljar3path=syncmljar3path.replace(/\\/g,'/');
  syncmljar3path='file:///'+syncmljar3path;

  paths[0]=tnjarpath;
  paths[1]=syncmljar1path;
  paths[2]=syncmljar2path;
  paths[3]=syncmljar3path;
  
  cl = new java.net.URLClassLoader(_toJavaUrlArray(paths));
  loadedClass = cl.loadClass("thundernote.ThunderNote");
  classInst = loadedClass.newInstance();
  
  serverurl=urlLine.value;
  foldername=folderLine.value;
  uid=uidLine.value;
  pwd=pwdLine.value;
  
  classInst.setConnectionParameters(serverurl,foldername,'','',uid,pwd);
  
  var request =  new XMLHttpRequest();
  if(request==null) alert('NULL');
  //if(classInst.initializeConnection())
  //{
    alert('ok');
  //}
  //else
  //  alert('An error occured initializing the connection : '+classInst.getLastError());
  */

  //statusLine.value="Retrieving Document Titles...";
  //var docTitles=__HELIPAD.getDocTitles(uid,pwd);
  //alert(docTitles.length+' titles found');
  //for(counter=0;counter<docTitles.length;counter++)
  //{
  //  alert('Doc '+counter+' Title : '+docTitles[counter].title);
  //  alert('Doc '+counter+' ID : '+docTitles[counter].id);
  //}

  
  
  
  //alert(docs.length+' docs found');
  //for(counter=0;counter<docs.length;counter++)
  //{
  //  alert('Doc '+counter+' Title : '+docs[counter].title);
  //  alert('Doc '+counter+' ID : '+docs[counter].id);
  //  alert('Doc '+counter+' TNAN : '+docs[counter].thunderNoteID);
  //  alert('Doc '+counter+' Tags : '+docs[counter].tags.length);
  //  if(docs[counter].tags.length>0)
  //  {
  //    for(counter2=0;counter2<docs[counter].tags.length;counter2++)
  //    {
  //      alert('Doc '+counter+' Tag '+counter2+' value : '+docs[counter].tags[counter2].name);
  //    }
  //  }
  //}




  //statusLine.value="Detecting server version...";
  //var dsServerVersion=__SYNCML.getDSVersion(serverurl);
  
  //if(dsServerVersion!=null)
  //{
  //  if(dsServerVersion!='')
  //  {
  //    alert(dsServerVersion);
  //  }
  //  else
  //    alert(__SYNCML.getLastError());
  // }
  //else
  //  alert(__SYNCML.getLastError());
    
//   try
//   {
//    alert(__SYNCML.getDSVersion(serverurl));
//    alert(__SYNCML.getLastError());
//   }
//   catch(ee)
//   {
//    alert('aa');
//   } 
  
  
  
}


//function showHelp()
//{
//  var cl = new java.net.URLClassLoader(_toJavaUrlArray(['file:///C:/Users/Michael/Desktop/Development Projects/ThunderNote/3.0/src/components/thundernote.jar']));
//  alert(cl);
//  var loadedClass = cl.loadClass("thundernote.ThunderNote");
//  alert(loadedClass);
//  var classInst = loadedClass.newInstance();
//  alert(classInst);
//  alert(classInst.getVersion());
//}

